#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::log(const QString &message)
{
    ui->logViewer->append(message);
}

void Widget::on_btn_load_clicked()
{
    QString dbPath=QFileDialog::getExistingDirectory(this,"选择数据目录",qApp->applicationDirPath());
    if(dbPath.isEmpty())
        return;

    if(rdb.open(dbPath))
    {
        log("数据库已加载");
        ui->btn_load->setEnabled(false);
    }
    else
        log("数据库无法加载");
}

void Widget::on_btn_submit_clicked()
{
    QString key=ui->in_key->text().trimmed();
    if(key.isEmpty())
        return;

    QString value=ui->in_value->text().trimmed();
    if(value.isEmpty())
    {
        QString result=rdb.get(key);
        log(LOG_GET.arg(key).arg(result));
    }
    else
    {
        if(rdb.put(key,value))
            log(LOG_PUT.arg(key).arg(value));
        ui->in_value->clear();
    }
}

void Widget::on_btn_remove_clicked()
{
    QString key=ui->in_removeKey->text().trimmed();
    if(key.isEmpty())
        return;

    if(rdb.remove(key))
        log(LOG_DEL.arg(key));
    ui->in_removeKey->clear();
}

void Widget::on_btn_clear_clicked()
{
    ui->in_key->clear();
}
